package com.killer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.killer.dao.TokenMapper;
import com.killer.dao.UserMapper;
import com.killer.pojo.Token;
import com.killer.pojo.User;
import com.killer.service.code.CodeService;
import com.killer.service.user.UserService;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Reference
    private CodeService codeService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private TokenMapper tokenMapper;

    @Override
    public void register(String email, String password, String code) {
        //调用验证码微服务检验验证码是否正确
        Integer result = codeService.validateCode(email, code);
        if (result == -1) {
            throw new RuntimeException("检验验证码超时");
        }
        if(result != 0){
            throw new RuntimeException("验证码错误或超时");
        }
        //判断是否已经注册过了
        User user = getUserByEmail(email);
        if (user != null) {
            throw new RuntimeException(email + "该账号已经被注册过了");
        }
        //保存用户
        saveUser(email, password);
    }

    @Override
    public User getUserByEmail(String email) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>().eq("email",email);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public String login(String email, String password) {
        //检验用户是否存在
        User user = getUserByEmail(email);
        if (user == null) {
            throw new RuntimeException("该账户不存在");
        }
        if (!StringUtils.isEquals(user.getPassword(), password)) {
            throw new RuntimeException("密码错误");
        }
        //判断是否已经生成过token
        Token token = tokenMapper.selectOne(new QueryWrapper<Token>().eq("email", email));
        if (token != null) {
            return token.getToken();
        }
        //生成并保存token
        return createToken(email);
    }

    @Override
    public Token getTokenbyToken(String token) {
        return tokenMapper.selectOne(new QueryWrapper<Token>().eq("token", token));
    }

    private String createToken(String email) {
        Token token=new Token();
        token.setEmail(email);
        token.setToken(UUID.randomUUID().toString());
        tokenMapper.insert(token);
        return token.getToken();
    }

    private void saveUser(String email, String password) {
        User user=new User();
        user.setEmail(email);
        user.setPassword(password);
        userMapper.insert(user);
    }
}
